import 'dart:io';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/user.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/event.dart';
import 'package:geomancy/tools/upload.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_input.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/gallery_util/index.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';

class SettingEditUserInfoPage extends StatefulWidget {
  const SettingEditUserInfoPage({super.key});

  @override
  State<SettingEditUserInfoPage> createState() => _SettingEditUserInfoPageState();
}

class _SettingEditUserInfoPageState extends State<SettingEditUserInfoPage> {
  File? avatarFile;
  String? avatarUrl;
  String? nickname;

  @override
  void initState() {
    super.initState();
    final user = context.read<UserProvider>().getUserInfo;
    nickname = user?.username;
    if (user?.avatar != null) {
      avatarUrl = user!.avatar!;
    }
    addEventListener();
  }

  @override
  void dispose() {
    removeEventListener();
    super.dispose();
  }

  addEventListener() {
    eventListener.on(Constant.CROPAVATAR, (arg) {
      setState(() {
        avatarFile = arg;
      });
    });
  }
  removeEventListener() {
    eventListener.off(Constant.CROPAVATAR);
  }

  getValueHandle(String value) {
    setState(() {
      nickname = value;
    });
  }

  void openGalleryHandle() {
    GalleryUtils.openGallery(context,
        scene: GalleryScene.registerAvatar,
        type: RequestType.image,
        maxCount: 1
    );
  }

  ///上传头像
  Future<String?> uploadAvatar() async {
    if (avatarFile == null) return null;
    try {
      final result = await QiNiu.uploadImage(context, file: avatarFile!, type: UploadBucketType.userAvatar);
      return result?.url;
    } catch(e) {
      return null;
    }
  }

  ///提交
  Future confirmHandle() async {
    EasyLoading.show(status: '上传中...');
    final url = await uploadAvatar();
    final UserEditAPIData userParams = UserEditAPIData.fromJson({
      "username": nickname,
      "avatar": url
    });
    if (mounted) {
      final result = await UserAPI.edit(context: context, user: userParams);
      if (result) {
        EasyLoading.showSuccess('编辑成功');
      }
    }
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: ListView(
          physics: const ClampingScrollPhysics(),
          padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, 40.w),
          children: [
            const CommonTitleWidget(txt: '编辑资料'),
            Container(
              height: 830.w,
              margin: EdgeInsets.only(top: 20.w, bottom: 120.w),
              padding: EdgeInsets.only(top: 120.w, bottom: 140.w, left: 40.w, right: 40.w),
              decoration: BoxDecoration(
                  color: ColorStyle.themeLightColor,
                  border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                  borderRadius: BorderRadius.all(Radius.circular(60.w))
              ),
              child: Column(
                children: [
                  GestureDetector(
                    onTap: openGalleryHandle,
                    child: Container(
                        width: 300.w,
                        height: 300.w,
                        margin: EdgeInsets.only(bottom: 30.w),
                        decoration: BoxDecoration(
                            color: const Color.fromRGBO(72, 58, 44, 0.6),
                            border: Border.all(width: 6.w, color: const Color.fromRGBO(255, 85, 85, 1)),
                            borderRadius: BorderRadius.all(Radius.circular(150.w))
                        ),
                        child: Stack(
                          children: [
                            if (avatarFile != null || avatarUrl != null)
                              ClipOval(
                                child: SizedBox(
                                  width: 300.w,
                                  height: 300.w,
                                  child: avatarFile != null
                                    ? Image.file(avatarFile!, fit: BoxFit.contain)
                                    : ExtendedImage.network(avatarUrl!, fit: BoxFit.contain)
                                ),
                              ),
                            Center(child: Image.asset('assets/icons/icon_camera.png', width: 70.w))
                          ],
                        )
                    ),
                  ),
                  const CommonText(txt: '更换头像'),
                  const Expanded(child: SizedBox()),
                  Container(
                    decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 2.w, color: ColorStyle.borderColor)
                      ),
                    ),
                    child: CommonInputWidget(
                      hintText: '设置昵称',
                      defaultValue: nickname,
                      showBorder: false,
                      padding: EdgeInsets.zero,
                      maxLength: 10,
                      addonAfter: CommonText(txt: '（${nickname?.length}/10）'),
                      getValue: getValueHandle,
                    ),
                  ),
                ],
              ),
            ),
            Center(child: CommonBtnWidget(txt: '提交', size: Size(590.w, 80.w), onTap: confirmHandle))
          ],
        ),
      ),
    );
  }
}
